//
//  WHYPicturePickerViewController.swift
//  照片选择
//
//  Created by 王洪运 on 15/12/2.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit

private let WHYPicturePickerViewCellID = "WHYPicturePickerViewCellID"
private let WHYPicturePickerMaxCount = 3

class WHYPicturePickerViewController: UICollectionViewController {

    //    当前点击cell的索引
    private var currentIndex = 0
    
    //    照片数组
    lazy var pictures = [UIImage]()
    
    init () {
        let flowLayout = WHYPicturePickerViewLayout()
        
        super.init(collectionViewLayout: flowLayout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.registerClass(WHYPicturePickerViewCell.self, forCellWithReuseIdentifier: WHYPicturePickerViewCellID)
        
        collectionView?.backgroundColor = UIColor.whiteColor()
    }
    

    
// MARK: - WHYPicturePickerViewLayout
    private class WHYPicturePickerViewLayout: UICollectionViewFlowLayout {
        
        private override func prepareLayout() {
            super.prepareLayout()
            
            let margin: CGFloat = UIScreen.mainScreen().scale * 4
            let count: CGFloat = 4
            
            let w = (UIScreen.mainScreen().bounds.width - (count + 1) * margin) / count
            
            itemSize = CGSize(width: w, height: w)
            
            minimumInteritemSpacing = 0
            minimumLineSpacing = margin
            
            sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)

        }
        
    }

}

// MARK: - 数据源和代理函数
extension WHYPicturePickerViewController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        // 保证末尾有一个加号按钮，如果达到上限，不显示 + 按钮！
//        return pictures.count + (pictures.count == WHYPicturePickerMaxCount ? 0 : 1)
        
        /*
        修改
        原因： 因为removeAtIndex方法底层会调用数据源方法，当调用数据源方法的时候图片并没有被马上删除，这时候我们返回的数据源数量减少了一个，但是cell数量并没有减少，所以会崩溃！！！！
        */
        
        return pictures.count + 1
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WHYPicturePickerViewCellID, forIndexPath: indexPath) as! WHYPicturePickerViewCell
        
        cell.delegate = self
        cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil
        
//        当添加了9张图片时，隐藏最后一个添加按钮
        cell.hidden = (indexPath.item == WHYPicturePickerMaxCount)
        
        return cell
    }
    
}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension WHYPicturePickerViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let scaleImage = image.scaleToWidth(600)
        
//        QL2(currentIndex)
//        QLShortLine()
//        QL2(pictures.count)
//        防止点击已经添加的图片时，再次添加一个图片
//        当点击已经添加的图片时，替换此图片
        if currentIndex < pictures.count {
            pictures[currentIndex] = scaleImage
        }else {
            pictures.append(scaleImage)
        }
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}

// MARK: - WHYPicturePickerViewCellDelegate
extension WHYPicturePickerViewController: WHYPicturePickerViewCellDelegate {
    
    @objc private func picturePickerViewCellDidAddPhoto(cell: WHYPicturePickerViewCell) {
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            QL4("不允许访问照片库")
            return
        }
        
//        记录当前点击的cell的索引
        currentIndex = collectionView!.indexPathForCell(cell)!.item
        
        let picker = UIImagePickerController()
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
    }
    
    @objc private func picturePickerViewCellDidRemovePhoto(cell: WHYPicturePickerViewCell) {
        let index = collectionView!.indexPathForCell(cell)!
        
//        保证点击的cell是有图片的cell
        if index.item >= pictures.count {
            return
        }
        
        pictures.removeAtIndex(index.item)
        collectionView?.deleteItemsAtIndexPaths([index])
        
        if pictures.count < (WHYPicturePickerMaxCount - 1) {
            return
        }

//        刷新数据，显示添加按钮
        delay(0.5) { () -> () in
            let lastIndex = NSIndexPath(forItem: self.pictures.count, inSection: index.section)
            self.collectionView?.reloadItemsAtIndexPaths([lastIndex])
        }
    }
    
}

// MARK: - WHYPicturePickerViewCell
private class WHYPicturePickerViewCell: UICollectionViewCell {
    
    private var image: UIImage? {
        didSet {
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            removeButton.hidden = (image == nil)
        }
    }
    
    weak var delegate: WHYPicturePickerViewCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
// MARK: - 监听事件
    @objc func addPhoto() {
        delegate?.picturePickerViewCellDidAddPhoto!(self)
    }
    
    @objc func removePhoto() {
        delegate?.picturePickerViewCellDidRemovePhoto!(self)
    }
    
// MARK: - 设置UI
    private func setupUI () {
        addSubview(addButton)
        addSubview(removeButton)
        
        addButton.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
        
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(self)
        }
        
        addButton.imageView?.contentMode = .ScaleAspectFill
        
        addButton.addTarget(self, action: "addPhoto", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePhoto", forControlEvents: .TouchUpInside)
        
    }
    
// MARK: - 懒加载子控件
    private lazy var addButton: UIButton = UIButton(imageName: "compose_pic_add",
        backImageName: nil)
    
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close",
        backImageName: nil)
    
}

@objc
private protocol WHYPicturePickerViewCellDelegate: NSObjectProtocol {
    
    optional func picturePickerViewCellDidAddPhoto(cell: WHYPicturePickerViewCell)
    
    optional func picturePickerViewCellDidRemovePhoto(cell: WHYPicturePickerViewCell)
    
}






